package com.github.kezhenxu94.playground.java.concurrent;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

public class BoundedHashSet<T> {
	
	protected Semaphore	semaphore;
	protected Set<T>	set;
	
	public BoundedHashSet(int bound) {
		this.semaphore = new Semaphore(bound);
		this.set = Collections.synchronizedSet(new HashSet<>());
	}
	
	public boolean add(T t) throws InterruptedException {
		semaphore.acquire();
		boolean wasAdded = false;
		try {
			wasAdded = set.add(t);
			return wasAdded;
		} finally {
			if (!wasAdded)
				semaphore.release(); // 没有添加，释放该方法开始时获取的那一个信号
		}
	}
	
	public boolean remove(Object obj) {
		boolean wasRemoved = set.remove(obj);
		if (wasRemoved)
			semaphore.release();
		return wasRemoved;
	}
	
	public boolean isEmpty() {
		return semaphore.availablePermits() == 0;
	}
}
